const express = require("express");
const { success, fail } = require("../../utils/response");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { NotFound, Unauthorized } = require("http-errors");
const { Op } = require("sequelize");
const { User } = require("../../models");

const router = express.Router();
const JWT_SECKET = process.env.JWT_SECKET;

router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  try {
    const user = await User.findOne({
      where: {
        [Op.or]: [
          {
            username: username,
          },
          { email: username },
        ],
      },
    });
    if (!user) {
      throw new NotFound("用户不存在");
    }
    console.log("user", user);

    // 角色
    if (user.role !== 100) {
      throw new Unauthorized("非管理员");
    }
    // 验证pwd
    const valid = bcrypt.compareSync(password, user.password);
    if (!valid) {
      throw new Unauthorized("验证失败");
    }
    // 生成token
    const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECKET);
    success(res, "登录成功", { token });
  } catch (error) {
    fail(res, error);
  }
});
// 后台注册 /admin/auth/sign_up
router.post("/sign_up", async (req, res) => {
  try {
    const { username, nickname, password, email, role } = req.body;
    const newUser = {
      username,
      nickname,
      // 已在model中hash加密
      password,
      email,
      sex: 0,
      // 后台默认角色 普通用户
      role: role || 0,
    };
    const user = await User.create(newUser);
    // Reflect.deleteProperty(user, "password");
    delete user.dataValues.password;
    success(res, "注册成功", user);
  } catch (error) {
    fail(res, error);
  }
});

// 退出登录
router.post("/logout", async (req, res) => {
  // 清除token
  success(res, "退出成功");
});

module.exports = router;
